import asyncio
import threading
from .logger import get_logger
from typing import (
    Callable,
    Any,
)
try:
    import uvloop
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
    pass

logger = get_logger("global")
def custom_hook(args: threading.ExceptHookArgs):
    logger.error(f"Exception in thread {args.thread.name}: {args.exc_value}")

threading.excepthook = custom_hook

def create_loop_thread(async_func: Callable[..., Any]):
    loop_future = asyncio.Future()
    event = threading.Event()
    def start_loop(loop_future: asyncio.Future):
        loop = asyncio.new_event_loop()
        loop_future.set_result(loop)
        event.set()  # 设置事件标志，表示线程已启动
        loop.run_forever()
    thread = threading.Thread(target=start_loop, args=(loop_future,))
    thread.start()
    event.wait(timeout=5.0)  # 等待线程启动
    loop:asyncio.AbstractEventLoop = loop_future.result()
    asyncio.run_coroutine_threadsafe(async_func(loop), loop)
    return loop, thread

def stop_loop_thread(loop: asyncio.AbstractEventLoop, thread: threading.Thread):
    tasks = asyncio.all_tasks(loop)
    for t in tasks:
        t.cancel()
    loop.stop()
    thread.join()